MessageView = BaseView:Extend()

local insert = table.insert
local remove = table.remove
local max_cache = 10
function MessageView:New()
    local o = MessageView.super.New(self)
    o.abName = "ui_common"
    o.resName = "MessageView"
    o.layer = ENUM.UI_LAYER.TOP
    o.msg_item = {}
    o.msg_list = {}
    return o
end

function MessageView:StartTimer()
    self.timer_id = TimerQuest:GetInstance():AddRepeat(function()
        self:HandlerMessage()
    end,0.2,-1)
end

function MessageView:loadSuccess()

    self:StartTimer()

    if self.needShowMessageSimple then
        self:ShowMessageSimple(self.msg)
    end
end

function MessageView:ShowMessageSimple(msg)
    self.msg = msg
    if self.loaded then
        self.needShowMessageSimple = false
        if #self.msg_list == 0 then
            self:HandlerMessage(self.msg)
        else
            insert(self.msg_list,1,msg)
            if #self.msg_list > max_cache then
                for i = #self.msg_list , max_cache + 1 , -1 do
                    self.msg_list[i] = nil
                end
            end
            self:StartTimer()
        end
    else
        self.needShowMessageSimple = true
    end
end

function MessageView:HandlerMessage(msg)
    if msg then
        self:ShowItem(msg)
    else
        local _msg = remove(self.msg_list,#self.msg_list)
        self:ShowItem(_msg)
    end
    if #self.msg_list == 0 then
        TimerQuest:GetInstance():ClearTimer(self.timer_id)
    end
end

function MessageView:ShowItem(msg)
    local msg_item
    if #self.item_list == 0 then
        msg_item = MessageItem:New(self.item_list)
        msg_item:SetMessageView(self)
    else
        msg_item = remove(self.item_list)
    end
    msg_item:SetData(msg)
end

function MessageView:PlayEndHandler(that)
    if #self.item_list >= max_cache then
        that:DeleteMe()
    else
        insert(self.item_list,that)
    end
end

function MessageView:InitEvent()

end

function MessageView:destroy_callback()
end

function MessageView:__delete()
    TimerQuest:GetInstance():ClearTimer(self.timer_id)
end